from abc import ABC, abstractmethod
from openai import OpenAI
import os

class TTSBase(ABC):
    """TTS基础类"""
    
    @abstractmethod
    def synthesize(self, text: str, character: str, **kwargs) -> bytes:
        """文本转语音"""
        pass
    
    @abstractmethod
    def clone_voice(self, audio_sample: str, **kwargs) -> str:
        """音色克隆"""
        pass

class IndexTTS(TTSBase):
    """IndexTTS-1.5 实现"""
    
    def __init__(self, api_key: str = None, base_url: str = "https://ai.gitee.com/v1"):
        self.api_key = api_key or os.getenv("INDEX_TTS_API_KEY")
        self.base_url = base_url
        self.client = OpenAI(base_url=base_url, api_key=self.api_key)
    
    def synthesize(self, text: str, character: str, **kwargs) -> bytes:
        """使用IndexTTS合成语音"""
        # 获取音色克隆链接（如果存在）
        prompt_audio_url = kwargs.get("prompt_audio_url", None)
        
        extra_body = {}
        if prompt_audio_url:
            extra_body["prompt_audio_url"] = prompt_audio_url
            
        response = self.client.audio.speech.create(
            input=text,
            model="IndexTTS-1.5",
            voice=character,
            extra_body=extra_body
        )
        
        return response.content
    
    def clone_voice(self, audio_sample: str, **kwargs) -> str:
        """音色克隆 - 在IndexTTS中通过prompt_audio_url实现"""
        # 这里返回音频样本URL，实际使用时需要上传音频文件并获取URL
        return audio_sample

class StepAudioTTS(TTSBase):
    """Step-Audio-TTS-3B 实现"""
    
    def __init__(self, api_key: str = None, base_url: str = "https://ai.gitee.com/v1"):
        self.api_key = api_key or os.getenv("STEP_AUDIO_API_KEY")
        self.base_url = base_url
        self.client = OpenAI(base_url=base_url, api_key=self.api_key)
    
    def synthesize(self, text: str, character: str, **kwargs) -> bytes:
        """使用Step-Audio-TTS合成语音"""
        response = self.client.audio.speech.create(
            input=text,
            model="Step-Audio-TTS-3B",
            voice=character
        )
        
        return response.content
    
    def clone_voice(self, audio_sample: str, **kwargs) -> str:
        """音色克隆"""
        # 实现音色克隆逻辑
        return audio_sample

class TTSFactory:
    """TTS工厂 - 支持多种TTS引擎"""
    
    _tts_engines = {
        "index_tts": IndexTTS,
        "step_audio": StepAudioTTS
    }
    
    @classmethod
    def create_tts(cls, tts_type: str = "index_tts", **config) -> TTSBase:
        """创建TTS实例，默认使用IndexTTS"""
        if tts_type not in cls._tts_engines:
            raise ValueError(f"Unsupported TTS type: {tts_type}")
        
        tts_class = cls._tts_engines[tts_type]
        return tts_class(**config)
    
    @classmethod
    def register_tts(cls, name: str, tts_class: type):
        """注册新的TTS引擎"""
        cls._tts_engines[name] = tts_class